const app = getApp();
const util = require('../../../utils/util.js')
Page({
  data: {
    mobile:'',
    code:'',
    time:60,
    can_send_code:true,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad:function(){

  },

  BackPage() {
    var pages_length = getCurrentPages().length;
    if(pages_length > 1){
      wx.navigateBack({
        delta: 1
      });
    }else{
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
  },

  nameInput:function(e){
    this.setData({
      mobile:e.detail.value
    })
  },
  codeInput:function(e){
    this.setData({
      code:e.detail.value
    })
  },

  //发送验证码
  code() {
    var that = this;
    if(that.data.mobile == ''){
      util.fail("请输入手机号码", that)
      return
    }
    if (!(/^1[34578]\d{9}$/.test(that.data.mobile))) {
      util.fail("手机号码格式不正确", that)
      return
    }
    util.request('send_code/sendCode',
      { mobile: that.data.mobile },
      function (data) {
        if (data.code == 1) {
          that.setData({
            can_send_code:false
          });
          that.time();
          util.success(data.msg);
        } else {
          util.fail(data.msg, that);
        }
      });
  },


  time(){
    var _this = this;
    if(!_this.data.can_send_code){
      var timeout = setInterval(function () {
        if(_this.data.time > 1){
          _this.setData({
            time:_this.data.time-1
          })
        }else{
          _this.setData({
            can_send_code:true,
            time:60,
          })
          clearInterval(timeout);
        }

      },1000)
    }
  },
  
  //提交
  formSubmit: function (e) {
    console.log(e.detail.userInfo)
    var that = this
    if (that.data.mobile == ''){
      util.fail("请输入手机号码", that)
      return
    }
    if (that.data.code == '') {
      util.fail("请输入验证码", that)
      return
    }
    var param = {mobile:that.data.mobile,code:that.data.code,openid:app.globalData.openId};
    if(e.detail.userInfo){
      param['nickname'] = e.detail.userInfo.nickName;
      param['image'] = e.detail.userInfo.avatarUrl;
      param['gender'] = e.detail.userInfo.gender;
    }

    console.log(param);

    util.request('site/register',param, function (data) {
      if(data.code == 1){
        app.globalData.parent = data.data.user;
        app.globalData.login = true;
        wx.navigateBack({
          delta: 2,
          fail:function () {
            wx.switchTab({
              url: '../../index/index',
            })
          }
        })
      }else{
        util.fail(data.msg,that);
      }
    });
  },
})
